package com.example.aiinterview.controller;

import com.example.aiinterview.model.Interview;
import com.example.aiinterview.model.InterviewQuestion;
import com.example.aiinterview.model.User;
import com.example.aiinterview.model.ChatMessage;
import com.example.aiinterview.service.InterviewService;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 面试流程控制器
 * 处理面试相关的页面跳转和业务逻辑
 */
@Slf4j
@Controller
@RequiredArgsConstructor
public class InterviewController {

    private final InterviewService interviewService;
    private final UserService userService;

    /**
     * 显示面试主页面
     */
    @GetMapping("/interview")
    public String showInterviewPage(Model model, Authentication authentication) {
        try {
            User user = userService.findByUsername(authentication.getName());
            model.addAttribute("user", user);
            return "interview";
        } catch (Exception e) {
            log.error("加载面试页面失败", e);
            model.addAttribute("errorMessage", "系统错误，请稍后重试");
            return "interview";
        }
    }

    /**
     * 开始新的面试
     */
    @PostMapping("/interview/start")
    @Transactional
    public String startInterview(@RequestParam(value = "resumeFile", required = false) MultipartFile file,
                                 @RequestParam(value = "resumeText", required = false) String resumeText,
                                 @RequestParam("jobPosition") String jobPosition,
                                 Authentication authentication,
                                 RedirectAttributes redirectAttributes) {
        try {
            log.info("开始创建面试，职位: {}", jobPosition);

            // 验证简历内容输入
            String resumeContent = validateAndExtractResumeContent(file, resumeText, redirectAttributes);
            if (resumeContent == null) {
                return "redirect:/interview";
            }

            // 创建面试记录
            User user = userService.findByUsername(authentication.getName());
            Interview interview = interviewService.createNewInterview(user, resumeContent, jobPosition);
            log.info("面试创建成功，ID: {}", interview.getId());

            // 生成并保存第一个AI问题
            generateAndSaveFirstQuestion(interview);

            return "redirect:/chat-interview/" + interview.getId();

        } catch (IOException e) {
            log.error("文件处理错误", e);
            redirectAttributes.addFlashAttribute("errorMessage", "文件处理错误: " + e.getMessage());
        } catch (Exception e) {
            log.error("启动面试时出错", e);
            redirectAttributes.addFlashAttribute("errorMessage", "系统错误，请稍后重试");
        }
        return "redirect:/interview";
    }

    /**
     * 处理面试问答流程
     */
    @GetMapping("/interview/process/{interviewId}")
    public String processInterview(@PathVariable Long interviewId,
                                   @RequestParam int question,
                                   Authentication authentication,
                                   Model model) {
        try {
            User user = userService.findByUsername(authentication.getName());
            Interview interview = interviewService.findById(interviewId);

            if (!isInterviewAccessible(interview, user)) {
                return "redirect:/interview";
            }

            Optional<InterviewQuestion> currentQuestion = getCurrentQuestion(interview, question);
            if (currentQuestion.isEmpty()) {
                // 所有问题已回答，跳转到结果页面
                interviewService.evaluateAnswersAndFinalize(interview);
                return "redirect:/result/" + interviewId;
            }

            setupInterviewModel(model, interview, currentQuestion.get(), question);
            return "interview-process";

        } catch (Exception e) {
            log.error("处理面试流程失败，interviewId: {}", interviewId, e);
            model.addAttribute("errorMessage", "处理失败，请重试");
            return "redirect:/interview";
        }
    }

    /**
     * 提交用户答案
     */
    @PostMapping("/interview/answer/{interviewId}/{questionNumber}")
    public String submitAnswer(@PathVariable Long interviewId,
                               @PathVariable int questionNumber,
                               @RequestParam("answer") String answer,
                               Authentication authentication) {
        try {
            User user = userService.findByUsername(authentication.getName());
            Interview interview = interviewService.findById(interviewId);

            if (!isInterviewAccessible(interview, user)) {
                return "redirect:/interview";
            }

            interviewService.saveUserAnswer(interview, questionNumber, answer);
            int nextQuestion = questionNumber + 1;

            return "redirect:/interview/process/" + interviewId + "?question=" + nextQuestion;

        } catch (Exception e) {
            log.error("提交答案失败，interviewId: {}, question: {}", interviewId, questionNumber, e);
            return "redirect:/interview";
        }
    }

    /**
     * 显示面试结果
     */
    @GetMapping("/result/{interviewId}")
    public String showResult(@PathVariable Long interviewId,
                             Authentication authentication,
                             Model model) {
        try {
            User user = userService.findByUsername(authentication.getName());
            Interview interview = interviewService.findById(interviewId);

            if (!isInterviewAccessible(interview, user)) {
                return "redirect:/interview";
            }

            model.addAttribute("interview", interview);
            model.addAttribute("questions", interview.getQuestions());
            return "result";

        } catch (Exception e) {
            log.error("加载面试结果失败，interviewId: {}", interviewId, e);
            model.addAttribute("errorMessage", "加载结果失败");
            return "redirect:/interview";
        }
    }

    /**
     * 显示用户历史面试记录
     */
    @GetMapping("/interviews")
    public String showUserInterviews(Authentication authentication, Model model) {
        try {
            User user = userService.findByUsername(authentication.getName());
            List<Interview> interviews = interviewService.findByUser(user);
            model.addAttribute("interviews", interviews);
            return "interview-history";
        } catch (Exception e) {
            log.error("加载面试历史失败", e);
            model.addAttribute("errorMessage", "加载历史记录失败");
            return "interview-history";
        }
    }

    /**
     * 显示聊天式面试页面
     */
    @GetMapping("/chat-interview/{interviewId}")
    public String showChatInterview(@PathVariable Long interviewId,
                                    Authentication authentication,
                                    Model model,
                                    RedirectAttributes redirectAttributes) {
        try {
            log.info("加载聊天面试页面，ID: {}", interviewId);

            // 参数验证
            if (!isValidInterviewId(interviewId)) {
                redirectAttributes.addFlashAttribute("errorMessage", "无效的面试ID");
                return "redirect:/interview";
            }

            User user = userService.findByUsername(authentication.getName());
            Interview interview = interviewService.findById(interviewId);

            if (!isInterviewAccessible(interview, user)) {
                redirectAttributes.addFlashAttribute("errorMessage", "无权访问该面试");
                return "redirect:/interview";
            }

            // 初始化面试参数
            initializeInterviewParameters(interview);
            setupChatInterviewModel(model, interview);

            log.info("聊天面试页面加载成功，当前问题: {}/{}",
                    interview.getCurrentQuestionNumber(), interview.getTotalQuestions());

            return "chat-interview";

        } catch (Exception e) {
            log.error("加载聊天面试页面失败，interviewId: {}", interviewId, e);
            redirectAttributes.addFlashAttribute("errorMessage", "加载失败: " + e.getMessage());
            return "redirect:/interview";
        }
    }

    // ========== 私有辅助方法 ==========

    /**
     * 验证并提取简历内容
     */
    private String validateAndExtractResumeContent(MultipartFile file, String resumeText,
                                                   RedirectAttributes redirectAttributes) throws IOException {
        if (file != null && !file.isEmpty()) {
            log.info("处理上传文件: {}", file.getOriginalFilename());
            return interviewService.extractTextFromFile(file);
        } else if (resumeText != null && !resumeText.trim().isEmpty()) {
            log.info("处理文本简历");
            return resumeText.trim();
        } else {
            log.warn("未提供简历内容");
            redirectAttributes.addFlashAttribute("errorMessage",
                    "请提供简历内容（文件上传或文本输入）");
            return null;
        }
    }

    /**
     * 生成并保存第一个问题
     */
    private void generateAndSaveFirstQuestion(Interview interview) {
        try {
            String firstQuestion = generateFirstQuestion(interview);
            ChatMessage aiMessage = createChatMessage(interview, firstQuestion, ChatMessage.MessageSender.AI);
            interview.addChatMessage(aiMessage);
            interviewService.saveInterview(interview);

            log.info("第一个问题生成成功，interviewId: {}", interview.getId());
        } catch (Exception e) {
            log.error("生成第一个问题失败，使用备用问题", e);
            useFallbackQuestion(interview);
        }
    }

    /**
     * 检查面试是否可访问
     */
    private boolean isInterviewAccessible(Interview interview, User user) {
        return interview != null &&
                interview.getUser() != null &&
                interview.getUser().getId().equals(user.getId());
    }

    /**
     * 获取当前问题
     */
    private Optional<InterviewQuestion> getCurrentQuestion(Interview interview, int questionNumber) {
        return interview.getQuestions().stream()
                .filter(q -> q.getQuestionNumber() == questionNumber)
                .findFirst();
    }

    /**
     * 设置面试模型数据
     */
    private void setupInterviewModel(Model model, Interview interview,
                                     InterviewQuestion currentQuestion, int questionNumber) {
        model.addAttribute("interview", interview);
        model.addAttribute("currentQuestion", currentQuestion);
        model.addAttribute("totalQuestions", interview.getQuestions().size());
        model.addAttribute("currentQuestionNumber", questionNumber);
    }

    /**
     * 验证面试ID有效性
     */
    private boolean isValidInterviewId(Long interviewId) {
        return interviewId != null && interviewId > 0;
    }

    /**
     * 初始化面试参数
     */
    private void initializeInterviewParameters(Interview interview) {
        if (interview.getCurrentQuestionNumber() == null) {
            interview.setCurrentQuestionNumber(1);
        }
        if (interview.getTotalQuestions() == null) {
            interview.setTotalQuestions(5);
        }
    }

    /**
     * 设置聊天面试模型数据
     */
    private void setupChatInterviewModel(Model model, Interview interview) {
        model.addAttribute("interview", interview);
        model.addAttribute("currentQuestionNumber", interview.getCurrentQuestionNumber());
        model.addAttribute("totalQuestions", interview.getTotalQuestions());
        model.addAttribute("resumeSummary", interview.getResumeSummary());
    }

    /**
     * 创建聊天消息对象
     */
    private ChatMessage createChatMessage(Interview interview, String content,
                                          ChatMessage.MessageSender sender) {
        ChatMessage message = new ChatMessage();
        message.setInterview(interview);
        message.setSender(sender);
        message.setContent(content);
        message.setTimestamp(LocalDateTime.now());
        return message;
    }

    /**
     * 使用备用问题
     */
    private void useFallbackQuestion(Interview interview) {
        try {
            String fallbackQuestion = String.format("请介绍一下您与%s相关的经验",
                    interview.getJobPosition() != null ? interview.getJobPosition() : "该职位");
            ChatMessage aiMessage = createChatMessage(interview, fallbackQuestion,
                    ChatMessage.MessageSender.AI);
            interview.addChatMessage(aiMessage);
            interviewService.saveInterview(interview);
            log.info("使用备用问题成功");
        } catch (Exception ex) {
            log.error("保存备用问题失败", ex);
        }
    }

    /**
     * 生成第一个问题（原有方法保留，内容不变）
     */
    private String generateFirstQuestion(Interview interview) {
        // 原有实现保持不变
        try {
            StringBuilder context = new StringBuilder();
            // ... 原有实现
            return interviewService.generateFirstQuestion(context.toString());
        } catch (Exception e) {
            log.error("生成第一个问题失败", e);
            return String.format("请简单介绍一下您自己，并说明您为什么对这个%s感兴趣？",
                    interview.getJobPosition() != null ? interview.getJobPosition() : "职位");
        }
    }

    // 测试和调试页面方法保持不变
    @GetMapping("/test")
    public String testPage() {
        return "test-chat";
    }

    @GetMapping("/debug-interview/{interviewId}")
    public String debugInterview(@PathVariable Long interviewId,
                                 Authentication authentication,
                                 Model model,
                                 RedirectAttributes redirectAttributes) {
        // 原有实现保持不变
        try {
            User user = userService.findByUsername(authentication.getName());
            Interview interview = interviewService.findById(interviewId);
            model.addAttribute("interview", interview);
            model.addAttribute("user", user);
            return "debug-interview";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "调试失败：" + e.getMessage());
            return "redirect:/interview";
        }
    }
}